
local skynet = require "skynet"
local mysql = require "mysql"
local snax = require "snax"
local cluster = require "cluster"
local sharedata = require "sharedata"
local config_cmd = require "match_config"
local cjson = require "cjson"
local CMD = require "center_proto"
local brw = require "buffrw"
local db = require "dblib"
local print_r = require "print_r"

local Match ={}
local match_data = {}
local matching_user  = {}
local json_db = {}
local match_contrl_right={}
local bRunServerOk = false

local GameServerShareObj = nil
local centser_ser        = nil
local switch_flag        = 0

local tab_ser = {}

local client_msg = nil

-----------------------------  给比赛模块调用的  -----------------
--比赛模块发送给客户端   data:只包含有数据，没有把命令打包进
function accept.m_send_to_client(playerid, mcmd, scmd, data)
    centser_ser.post.send_GateMail(playerid, mcmd, scmd,data)
end

--比赛模块发送给多个客户端   data:只包含有数据，没有把命令打包进
function accept.m_send_to_mult_client(playerid_arr, mcmd, scmd, data)
    centser_ser.post.send_mult_GateMail(playerid_arr, mcmd, scmd,data)
end

--比赛模块发送给某个桌子信号
function accept.m_send_to_game(table_id, cmd_data)
    table_pre = string.sub(tostring(table_id),1,2)
    local table_addr = GameServerShareObj.tableobj[tonumber(table_pre)]
    skynet.error("[matchser] m_send_to_game: ",table_id,table_pre,table_addr)
    if table_addr then
        skynet.send(table_addr, "lua","ToGame",cmd_data)
    end
end

--比赛模块发送给某个桌子信号
function accept.get_game_refresh_time(table_id, match_addr)
    table_pre = string.sub(tostring(table_id),1,2)
    local table_addr = GameServerShareObj.tableobj[tonumber(table_pre)]
    skynet.error("[matchser] get_game_refresh_time: ",table_id,table_pre,table_addr)
    if table_addr then
        skynet.send(table_addr, "lua","GetFefreshTime",match_addr)
    end
end

function accept.m_send_to_center(...)    
    centser_ser.post.update_user_state(...)   
end

------------------------  contrl <> match  ------------------------------
-- match -> contrl  
function accept.create_table(gameid, gameaddr, cmd_data)
    -- 查找各个房间的配置，并创建房间
    local sum_ser = 0
    if gameaddr then 
            local table_addr = GameServerShareObj.tableobj[gameaddr]
            skynet.error("[matchser] create_table table_addr: ",gameaddr,v,table_addr,tab_num)
            skynet.send(table_addr, "lua","ToGame",cmd_data)
    else
        for k,v in pairs(GameServerShareObj[CMD.GameType_Match][gameid]) do  
            sum_ser = sum_ser + 1 
        end
        
        local flag = 0        
        for k,v in pairs(GameServerShareObj[CMD.GameType_Match][gameid]) do  
            --todo rand server k = 桌号前两位，也就是对应服务器配置文件中的TableIdPre  v = 该服务器对应的agent地址
           if switch_flag % sum_ser == flag then 
                local table_addr = GameServerShareObj.tableobj[k]
                skynet.error("[matchser] create_table table_addr: ",k,v,table_addr,tab_num)
                skynet.send(table_addr, "lua","ToGame",cmd_data)
                switch_flag = switch_flag + 1
                break
            end
            flag = flag +1
        end
    end
end

-- match -> contrl
function accept.recv_match_state(match_number, state, num)
    skynet.error("[matchser] recv_match_state ",match_number, state, num)
    for k, v in ipairs(match_data) do
        if v.match_number == match_number and v.match_type == CMD.MatchType_fullmatch and state == CMD.MatchState_Matching then
            skynet.error("[matchser] recv_match_state start new matchser")
            local ser_addr =  skynet.newservice(v.ser_name)
            table.insert(v.addrlist, ser_addr)
            skynet.send(ser_addr, "lua","start",  v.jsonobj)

            v.state = CMD.MatchState_ReadyMatch
            v.num   = 0

        elseif v.match_number == match_number then
            v.state = state
            v.num   = num
        end
    end
end

function accept.end_single_matchser(match_number, addr)

    for k, v in ipairs(match_data) do
        if v.match_number == match_number  then
            for k2,v2 in pairs(v.addrlist) do
                local laddr = v2
                if laddr == addr then
                    skynet.send(laddr, "lua","exit")
                    table.remove(v.addrlist, k2)
                    break
                end
            end
        end
    end
end

----------------------------   传送消息 apid  ------------------------

--游戏服发送给比赛模块
function accept.recv_from_game(scmd,data)

    if scmd == CMD.Sub_RecvCreateMatchTable then
        local addr, result, tablecount,firsttableid = string.unpack("<i4<i4<i4<i4", data, 5)
        skynet.error("[matchser] recv_from_game： ",addr, result, tablecount,firsttableid)
        if result == 1 then
            skynet.send(addr,"lua","recv_create_table", data)
            local tid = math.floor(firsttableid / 10000)
        --    if  tab_ser[tid] == nil then
         --       tab_ser[tid] = 0
        --    end
        --    tab_ser[tid] = tab_ser[tid] + tablecount                                            --存贮桌子的现在开桌数量
        end
    else
        Match.game_send_to_match(scmd, data)
    end
end


--客户端上来的消息，发给比赛模块
function Match.client_send_to_match(userid,scmd, data)
   -- local match_addr = string.unpack("<i4",data,  1)
    if matching_user[userid] then 
        skynet.send(matching_user[userid].addr,"lua","recv_client", userid, scmd, data)
    end
end

--游戏服务器消息，发给比赛模块
function Match.game_send_to_match(scmd, data)
    local match_addr = string.unpack("<i4" ,data, 5)
    skynet.error("[matchser] game_send_to_match match_addr: ",match_addr)
    skynet.send(match_addr,"lua","recv_game", scmd, data)
end


function Match.recv_client_get_match_infor(scmd, data)
    local playerid = string.unpack("<i4" ,data, 1)
    if matching_user[playerid]  then
        skynet.error("[matchser] recv_client_get_match_infor find matching user ",playerid)
        return nil
    end
end

function Match.client_get_baoming_num(userid,scmd, data)

    local readbuf = brw.BuffRead.new(data)
	local send_date = brw.BuffWrite.new()
    local nMatchNumber = readbuf:int4()
    for k, v in ipairs(match_data) do
        if  v.match_number == nMatchNumber then
            send_date:int4(v.num)
            return {mcmd = CMD.Main_match_module, scmd = CMD.Sub_ModuleToMatch_BackBaoMingNum, msg = send_date.buff}
        end
       
    end
end

--取得排行榜
-- function Match.recv_gmatch_RankDate(scmd,data)

    -- Match.client_send_to_match(scmd, data)

    -- return nil
-- end

function Match.recv_gmatch_man_num(userid,scmd,data)
    local readbuf = brw.BuffRead.new(data)
    --local playerId    = readbuf:int4()
   -- skynet.error("[matchser] recv_gmatch_man_num "..playerId)
    local match_count = 0
    for k, v in ipairs(match_data) do
        if  v.state == CMD.MatchState_ReadyMatch 
            or v.state == CMD.MatchState_Match_end 
            or v.state == CMD.MatchState_Pauseing 
            or v.match_type == 2 and v.state == CMD.MatchState_Matching
            then
            match_count = match_count + 1
        end
    end

    local send_date = brw.BuffWrite.new()
    send_date:int4(match_count)

    for k, v in ipairs(match_data) do
        --if v.state == CMD.MatchState_ReadyMatch  and v.state == CMD.MatchState_ReadyMatch 
        if  v.state == CMD.MatchState_ReadyMatch 
            or v.state == CMD.MatchState_Match_end 
            or v.state == CMD.MatchState_Pauseing 
            or v.match_type == 2 and v.state == CMD.MatchState_Matching
            then
            send_date:int4(v.match_number)
            send_date:int4(v.num)
            if matching_user[userid] and matching_user[userid].match_num == v.match_number  then
                send_date:int4(CMD.MatchState_Registered)
            else
                send_date:int4(v.state)
            end
        end
       -- end
    end

    return {mcmd = CMD.Main_match_module, scmd = CMD.Sub_MatchToModule_UpdateNowNomberBack, msg = send_date.buff}
end

function Match.test_recv_gmatch_bao_ming(matchnum,playid)
    local send_data = brw.BuffWrite.new()
    send_data:int4(matchnum)
    send_data:int4(1)      
    send_data:int4(1)

    return {mcmd = CMD.Main_match_module, scmd = CMD.Sub_MatchToModule_PlayerBaoMingResult, msg = send_data.buff}
end

function Match.recv_gmatch_bao_ming(userid,scmd,data)
    local readbuf = brw.BuffRead.new(data)
    local nMatchNumber = readbuf:int4()
    --local bPlayerId    = readbuf:int4()

    if matching_user[userid] then  --已报了比赛（无论什么比赛）名
        skynet.error("[matchser] Match.recv_gmatch_bao_ming  has bao_min so return fail",userid,matching_user[userid].match_num)
        local BuffWrite = brw.BuffWrite.new() 
        BuffWrite:int4(nMatchNumber)
        BuffWrite:int4(2)--定时赛/人满开赛
        BuffWrite:int4(4) --0 钻石不足 1成功 2其他原因失败
        centser_ser.post.send_GateMail(userid,CMD.Main_match_module,CMD.Sub_MatchToModule_PlayerBaoMingResult,BuffWrite.buff)
        return nil
    end

    for k, v in ipairs(match_data) do
        if (v.state == CMD.MatchState_ReadyMatch or v.state == CMD.MatchState_Pauseing) and v.match_number == nMatchNumber then
            local match_addr = v.addrlist[#(v.addrlist)]
            if match_addr then
                skynet.error("[matchser] recv_gmatch_bao_ming send to match")
                skynet.send(match_addr,"lua","recv_client",userid, scmd, data)
            else
                skynet.error("[matchser] recv_gmatch_bao_ming no find bao_min match")
            end 
            break
            --return Match.test_recv_gmatch_bao_ming(nMatchNumber, bPlayerId);
        end
    end

    return nil
end

--客户端取得单个比赛信息
function Match.recv_get_match_single_info(userid,scmd,data)

    local readbuf = brw.BuffRead.new(data)
    local nMatchNumber = readbuf:int4()
    --local nPlayerId    = readbuf:int4()
    local send_date = brw.BuffWrite.new()
    -- 这里暂时使用buffrw的功能，效率不太高
    for k, v in ipairs(match_data) do

        --skynet.error("[matchser] recv_get_match_single_info ",nMatchNumber,nPlayerId,v.state,v.match_number)
        if ( v.state == CMD.MatchState_ReadyMatch 
            or v.state == CMD.MatchState_Match_end 
            or v.state == CMD.MatchState_Pauseing 
            or v.match_type == 2 and v.state == CMD.MatchState_Matching)
            and v.match_number == nMatchNumber then

            send_date:int4(v.match_number)
            send_date:int4(v.jsonobj["game_type"])
            send_date:int4(v.jsonobj["min_man"])
            send_date:int2(v.num)

            send_date:int1(v.jsonobj["icon_config"]["bao_min"])        -- 报名界面图片（前端的赛制说明图）
            send_date:int1(v.jsonobj["icon_config"]["baomin_name"])    --报名界面标题图片
            send_date:int1(v.jsonobj["icon_config"]["bao_min_sai_zi"]) --报名奖励图片   
                      
                  
           -- skynet.error("[matchser] recv_get_match_single_info FFFFFFFFFF ",v.match_number,v.jsonobj["game_type"],v.jsonobj["min_man"])
            return {mcmd = CMD.Main_match_module, scmd = CMD.Sub_MatchToModule_SingleBiSaiBack, msg = send_date.buff}
        end
    end

    --发送最终组织的数据到客户端
   
end

function match_getTimeStamp(daytime)
    local date_str =  os.date("%Y%m%d",os.time())
    local year = string.sub(date_str,1,4)
    local month = string.sub(date_str,5,6)
    local day = string.sub(date_str,7,8)
    local date_time = os.time(({day=day, month=month, year=year, hour=0, minute=0, second=0}))
    return date_time + tonumber(daytime)
end

--客户端取得比赛大厅信息
function Match.recv_get_match_hall_info(userid,scmd,data,offback) -- offback true: 断线重连 

    local readbuf = brw.BuffRead.new(data)
    --local playerid = readbuf:int4()
    local match_count = 0
    for k, v in ipairs(match_data) do
        if v.state == CMD.MatchState_ReadyMatch 
		  or v.state == CMD.MatchState_Match_end
		  or v.state == CMD.MatchState_Pauseing 
          or v.match_type == 2 and v.state == CMD.MatchState_Matching
        then
            match_count = match_count + 1
        end
    end
    skynet.error("[matchser] recv_get_match_hall_info userid match_count ",userid,match_count)

    
    local current_t = os.time()  --当前时间
    local MsgTime  = os.date("*t",current_t)
    local baseYear  = MsgTime.year
    local baseMonth = MsgTime.month
    local baseDay   = MsgTime.day
    local timeBase = os.time({day=baseDay, month=baseMonth, year=baseYear, hour=0, minute=0, second=0})
    current_t = current_t - timeBase
    
    local send_date = brw.BuffWrite.new()

    send_date:int4(match_count)
 
    -- 这里暂时使用buffrw的功能，效率不太高
    for k, v in ipairs(match_data) do
   
        if v.state == CMD.MatchState_ReadyMatch 
            or v.state == CMD.MatchState_Match_end 
            or v.state == CMD.MatchState_Pauseing
            or v.match_type == 2 and v.state == CMD.MatchState_Matching  
        then
            send_date:int4(v.match_number)
            send_date:int1(v.jsonobj["match_type"])
            if v.state == CMD.MatchState_ReadyMatch  and  matching_user[userid] 
                and matching_user[userid].match_num == v.match_number  then
                send_date:int1(CMD.MatchState_Registered)
            else
                send_date:int1(v.state)
            end
            local nPayType = v.jsonobj["pay_type"]
            local nPayNum  = v.jsonobj["pay_num"]

            send_date:int1( nPayType)

            send_date:int1(v.jsonobj["icon_config"]["hall_prize_icon"])         --to do
            --------------------test
            --v.jsonobj["start_time"] = 240 + os.time() - timeBase
            local start_t = match_getTimeStamp(v.jsonobj["start_time"]) - timeBase

            local diftime = 0
            if start_t > current_t then
                diftime = start_t - current_t 
            end
            --skynet.error("[matchser] recv_get_match_hall_info  ",start_t,current_t,diftime)
            send_date:Int4( start_t ) 
            send_date:Int4( diftime ) 

            send_date:int2(v.num)
            send_date:int2(v.jsonobj["max_man"])
            send_date:int4(nPayNum)
            send_date:str(v.jsonobj["match_name"],24)
        end
    end

    --发送最终组织的数据到客户端
    if offback then
        skynet.error("[matchser] recv_get_match_hall_info offback ")    
        centser_ser.post.send_GateMail(userid, CMD.Main_match_module, CMD.Sub_ModuleToMatch_BiSaiOffBackHall, send_date.buff)
    else   
        return {mcmd = CMD.Main_match_module, scmd = CMD.Sub_MatchToModule_BiSaiInfoBack, msg = send_date.buff}
    end
end


function accept.recv_user_addr(userid,match_number, match_addr,flag)
     skynet.error("[matchser] recv_user_addr ",userid, match_addr,flag)
    if matching_user[userid] then 
        if flag == 1 then        
            matching_user[userid].addr = match_addr
            matching_user[userid].match_num = match_number
        elseif flag == 0 then 
            matching_user[userid] = nil
        end
    else
        if flag == 1 then     
            matching_user[userid] = {addr =match_addr,match_num =match_number}
        elseif flag == 0 then 
            matching_user[userid] = nil
        end   
    end
end


--客户端发送数据到协调模块，协调模块再查表转发给比赛模块
function response.recv_from_client(conf)  

    if not client_msg then
        client_msg = {
            [CMD.Sub_ModuleToMatch_GetBiSaiInfoReq]   = Match.recv_get_match_hall_info,
            [CMD.Sub_ModuleToMatch_GetSingleBiSaiReq] = Match.recv_get_match_single_info,
            [CMD.Sub_ModuleToMatch_PlayerBaoMingReq]  = Match.recv_gmatch_bao_ming,
            [CMD.Sub_ModuleToMatch_UpdateNowNomberReq]= Match.recv_gmatch_man_num,
            [CMD.Sub_ModuleToMatch_BiSaiRankDataReq]  = Match.client_send_to_match,        -- 直接转给比赛模块
            [CMD.Sub_ModuleToMatch_CancelBaoMinReq]   = Match.client_send_to_match,        
            [CMD.Sub_ModuleToMatch_GetBiSaiRoomInfoReq]   = Match.client_send_to_match,
            [CMD.Sub_ModuleToMatch_BiSaiOffBack]   = Match.HallOffBackData, 
            [CMD.Sub_ModuleToMatch_BiSaiPreJoinBack] = Match.client_send_to_match,
            [CMD.Sub_ModuleToMatch_GetBiSaiHelpInfo] = Match.client_send_to_match,
            [CMD.Sub_ModuleToMatch_GetBaoMingNum] = Match.client_get_baoming_num,
            
        }
    end

    local scmd = conf.cmd
    --skynet.error("[matchser] recv_from_client scmd ",conf.playid,conf.cmd)
    local f = client_msg[scmd]
    if f then
        local ret = f(conf.playid,conf.cmd, conf.msg)
        return ret
    end
    skynet.error("[matchser] recv_from_client not find scmd ",conf.playid,conf.cmd)
    return nil
end

function Match.HallOffBackData(userid,scmd, data)

    Match.recv_get_match_hall_info(userid,scmd,data,true) --断线重连获取大厅数据
    
    Match.client_send_to_match(userid,scmd, data) 
end

function Match.CommitSingleSeveice(match_id, config_item)

    for k, v in ipairs(match_data) do
        if v.match_number == match_id then

            local ser_name = json_db["config"][tostring(config_item.match_type)]["lua_file"]
           
            v.ser_name      = ser_name
            v.match_number  = tonumber(config_item.match_number)
            v.jsonobj       = config_item
            v.match_type    = config_item.match_type
            v.state         = CMD.MatchState_RunServer 
            v.match_addr    = skynet.self()
            v.num           = 0

            skynet.error("[matchser] CommitSeveice : "..ser_name.." match_number:"..config_item.match_number)

            --如果是人满比赛，则只处理最后一个进程，其它进程只需自已关掉。
            local addr_s = v.addrlist[#(v.addrlist)]
            skynet.error("commit singleSeveice:", addr_s, #(v.addrlist))
            skynet.send(addr_s, "lua","exit")

            local ser_addr  =  skynet.newservice(ser_name)
            v.addrlist[#(v.addrlist)] = ser_addr
            skynet.send(ser_addr, "lua","start",  config_item)

            break
        end
    end
end

function Match.StartSingleSeveice(config_item)

    local index = #match_data + 1

    local ser_name = json_db["config"][tostring(config_item.match_type)]["lua_file"]
   
    match_data[index]               = match_data[index] or {}
    match_data[index].ser_name      = ser_name
    match_data[index].match_number  = tonumber(config_item.match_number)
    match_data[index].jsonobj       = config_item
    match_data[index].match_type    = config_item.match_type
    match_data[index].state         = CMD.MatchState_RunServer 
    match_data[index].match_addr    = skynet.self()
    match_data[index].num           = 0

    skynet.error("[matchser] StartSeveice : "..ser_name.." match_number:"..config_item.match_number)

    local ser_addr              =  skynet.newservice(ser_name)
    match_data[index].addrlist = match_data[index].addrlist or {}
    table.insert(match_data[index].addrlist, ser_addr)
    skynet.send(ser_addr, "lua","start",  config_item)
end

--启动各比赛服务
function Match.StartSeveice()
    skynet.error("[matchser] StartSeveice ")
    json_db = config_cmd.loadDb()
    if not json_db then
        skynet.error("config_cmd.loadDb  json format error ")
        return
    end
    for i=1, 100,1 do
        local config_item = json_db["match_config"]["config"][i]
        if config_item == nil then
            break
        end

        Match.StartSingleSeveice(config_item)
            
    end 

    --test
    Match.OnTimerFunction()

    bRunServerOk = true
end

--------------------  赛事操控   -----------------------------------

-- 取得赛事的状态值
function Match.get_match_state(match_id)  
    for k, v in ipairs(match_data) do
        if v.match_number == match_id then
            return v.state
        end
    end
    return nil
end

-- 删除某个赛事
function Match.del_match(match_id)  
    skynet.error("del_match "..match_id)
    for k, v in ipairs(json_db["match_config"]["config"]) do
        if v.match_number == match_id then
            skynet.error("del_match "..match_id)
            table.remove(json_db["match_config"]["config"],k)
            break
        end
    end
    return nil
end

-- 取得某个真实赛事初始值
function response.web_get_match_list()  
    local all_list = {["list"] = {}}
    local min_number = 1
    for k, v in ipairs(match_data) do
       local ret_json = {}
       ret_json["match_number"]     = v.match_number
       ret_json["match_name"]       = v.jsonobj.match_name
       ret_json["match_type"]       = v.jsonobj.match_type
       ret_json["game_type"]        = v.jsonobj.game_type
       ret_json["start_time"]       = v.jsonobj.start_time
       ret_json["min_man"]          = v.jsonobj.min_man
       ret_json["max_man"]          = v.jsonobj.max_man
       ret_json["win_man"]          = v.jsonobj.win_man
       ret_json["pay_num"]          = v.jsonobj.pay_num
       ret_json["pay_type"]         = v.jsonobj.pay_type
       ret_json["start_date"]       = v.jsonobj.start_date
       ret_json["end_date"]         = v.jsonobj.end_date
       ret_json["state"]            = v.state               
       
       if  v.match_number then
           if min_number < tonumber(v.match_number) then
                min_number = tonumber(v.match_number)
           end
       end
       skynet.error("pay_num",v.jsonobj.pay_num)
       skynet.error("min_man",v.jsonobj.min_man)
       local state_ctrl = {}
       if match_contrl_right[v.state] then
           skynet.error("------------------------- "..v.state.."  k="..k)
           for k, v in pairs(match_contrl_right[v.state]) do
                table.insert(state_ctrl, k)
           end
           skynet.error("------------------------- 11111111111111")
       end

       ret_json["contrl_right"]   = state_ctrl   
       table.insert(all_list["list"], ret_json)
    end

    all_list["max_number"]     = min_number  
    if #(all_list["list"]) == 0 then
        return [[{"error":"no match list"}]]
    end

    local json_str = cjson.encode(all_list)
    return json_str
end

--４：取得当前赛事列表(match_type）
function response.web_get_match_json(match_id)  

    skynet.error("web_get_match_json"..tonumber(match_id))

    for i=1, 100,1 do
        local config_item = json_db["match_config"]["config"][i]
        if config_item == nil then
            break
        end
        skynet.error("web_get_match_json  config_item.match_number = ", config_item.match_number)
        if tonumber(config_item.match_number) == tonumber(match_id) then
            local json_str = cjson.encode(config_item)
            skynet.error("web_get_match_json: ", json_str)
            return json_str
        end
    end
    skynet.error("web_get_match_json", match_id)
    return [[{"error":"not find match_id"}]]
end

--１：取得某个配置初始值
function response.web_get_defalut_match_json(match_type)  

    local min_number = 1
    for k, v in ipairs(match_data) do
       if  v.match_number then
           if min_number < tonumber(v.match_number) then
                min_number = tonumber(v.match_number)
           end
       end
    end

    return config_cmd.loaddefalut(min_number, match_type)
end

--３：提交一个新的配置
function response.web_commit_match_json(new, json_str)  
    local commit_number = 0
    
    skynet.error("web_commit_match_json "..string.len(json_str))

    local ok, jsonobj  = pcall(cjson.decode, json_str)
    if ok then
        skynet.error("response.web_commit_match_json ok : ")
        commit_number = tonumber(jsonobj.match_number)
        if jsonobj.match_number == nil then
            skynet.error("commit fail ,no match_number")
            return [[{"error":"commit fail ,no match_number"}]]   
        end
    end

    --这里进行必要的检查工作
    local bSet = false
    if new == 0 then
        for i=1, #(json_db["match_config"]["config"]),1 do
            local config_item = json_db["match_config"]["config"][i]
            if config_item and tonumber(config_item.match_number) == commit_number then
                json_db["match_config"]["config"][i] = jsonobj
                bSet = true
                Match.CommitSingleSeveice(commit_number, jsonobj)
                break
            end
        end
    end
    if new == 1 and not bSet then
        table.insert(json_db["match_config"]["config"], jsonobj)
        bSet = true
        Match.StartSingleSeveice(jsonobj)
        skynet.error("start a new match server ")
    end

    if bSet == true and config_cmd.saveDb(json_db) then
        return [[{"result":"commit ok"}]]   
    end

    if bSet == false then
        skynet.error("do not find the match_number", commit_number,new)
    end
    return [[{"error":"commit fail"}]]   
end

--５：状态执行：发布，删除，暂停，下线
function response.web_contrl_match(match_id, active_id) 

    if not bRunServerOk  then
        return [[{"error":"not run complete"}]]   
    end

    local match_sta = Match.get_match_state(match_id)  

    --做权限判断    
    if not match_contrl_right[match_sta] then
        skynet.error("web_contrl_match "..match_id.." "..active_id.." not find ".." state="..match_sta)
        return [[{"error":"match_sta error"}]]
    end
    if  not match_contrl_right[match_sta][active_id] then
        skynet.error("web_contrl_match "..match_id.." "..active_id.." not have right".." state="..match_sta)
        return [[{"error":"not right"}]]
    end

    skynet.error("web_contrl_match "..match_id.." active_id "..active_id)

    local bSetDb = false
    local bContrl = false
    for k, v in ipairs(match_data) do
        if v.match_number == match_id then
            for k2, add_r in ipairs(v.addrlist) do
                if active_id == CMD.MatchContrl_delete then
                    skynet.send(add_r, "lua","exit")
                else
                    skynet.send(add_r, "lua","contrl",  active_id)
		            bContrl = true
                end
            end

            if active_id == CMD.MatchContrl_delete then
                Match.del_match(match_id)
                table.remove(match_data, k)
                bSetDb = true
                break
            end
        end
    end

    if bSetDb and config_cmd.saveDb(json_db) then
        return [[{"result":"save delete ok"}]]              
    end

    if bContrl then
        return [[{"result":"contrl ok"}]]              
    end

    return [[{"error":"contrl fail"}]]                             
end

-- 6：取得可选择项定义
function response.web_get_select_def() 
    return config_cmd.load_select_def()                            
end
--------------------  end 赛事操控   -----------------------------------

function Match.Test()

    local rett = db.call("call Pr_LoadZhanJi5(31021);")
    skynet.error("---------------------------------")
    --print_r.pt(rett, 10)
    if rett then
        skynet.error("[matchser] Test rett len = ".. #(rett[1]))
        skynet.error("---------------------------------")
    end
    --skynet.error("szChair1Name = "..rett[1]["szChair1Name"])
end


function Match.OnTimerFunction()
    skynet.fork(function()
        while true do
            --Match.Test()
            skynet.sleep(100)    
        end
    end)
end

function Match.StopSeveiceByMatchId(match_id)
   for k, v in ipairs(match_data) do
        if match_data.match_id == match_id then
            --只能停止最后服务
            skynet.send(v.addrlist[#(v.addrlist)], "lua","exit")
        end
   end
end

--启动各比赛服务
function Match.StopSeveice()

   for k, v in ipairs(match_data) do
        for k2,v2 in pairs(v.addrlist) do
            skynet.send(v2, "lua","exit")
        end
   end
end

function init( ... )

	skynet.error("[matchser] match_ser server start:")
	snax.enablecluster()

    GameServerShareObj  = sharedata.query "GameServerShareObj"

    centser_ser = cluster.snax("center", "centerser")
    skynet.error("[matchser] match_ser centerser")

    match_contrl_right={
        [CMD.MatchState_RunServer]  = {[CMD.MacthContrl_publish] = 1, [CMD.MatchContrl_edit] = 1, [CMD.MatchContrl_delete] = 1, [CMD.MatchContrl_view] = 1},
        --[CMD.MatchState_ReadyMatch] = {[CMD.MacthContrl_not_publish] = 1, [CMD.MatchContrl_view] = 1, [CMD.MatchContrl_delete] = 1, [CMD.MacthContrl_pause] = 1},
        [CMD.MatchState_ReadyMatch] = {[CMD.MacthContrl_not_publish] = 1, [CMD.MatchContrl_view] = 1, [CMD.MacthContrl_pause] = 1},
        [CMD.MatchState_Matching]   = {[CMD.MatchContrl_view] = 1, [CMD.MacthContrl_pause] = 1},
        [CMD.MatchState_Match_end]  = {[CMD.MatchContrl_view] = 1, [CMD.MacthContrl_not_publish] = 1, [CMD.MatchContrl_delete] = 1},
        [CMD.MatchState_Pauseing]   = {[CMD.MatchContrl_view] = 1, [CMD.MacthContrl_not_online] = 1},
        [CMD.MatchState_Error]      = {[CMD.MatchContrl_view] = 1, [CMD.MatchContrl_delete] = 1},
        [CMD.MatchState_Invalid]    = {[CMD.MatchContrl_edit] = 1, [CMD.MatchContrl_delete] = 1}
    }

    skynet.timeout(1, function() Match.StartSeveice() end) 

end

function exit(...)
	skynet.error ("[matchser] match_ser server exit:", ...)
end
